package com.zhuimeng.Application.contorller;

import com.zhuimeng.Application.service.IUserSelvice;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/img")
@CrossOrigin
public class imageController {
    private String path = "img\\";


    @Autowired
    private IUserSelvice userSelvice;

    @RequestMapping("/uploader")
    public String uploaderImg(String username, MultipartFile file) {
        String fileName = UUID.randomUUID().toString();
        try (InputStream in = file.getInputStream();
             OutputStream out = new FileOutputStream(path + fileName);) {
            IOUtils.copy(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        userSelvice.updataHander(username, fileName);
        return fileName;
    }

    @RequestMapping("/getImg")
    public void getImage(String imageName, HttpServletResponse response) {
        try (InputStream in = new FileInputStream(path + imageName);
             OutputStream out = response.getOutputStream();) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
